/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.appspot.trick.it.admin.custom;

import com.appspot.trick.it.admin.controller.MainController;
import com.appspot.trick.it.admin.model.ArticleModel;
import java.util.List;
import javafx.concurrent.WorkerStateEvent;
import javafx.event.EventHandler;
import javafx.scene.control.TreeItem;

/**
 *
 * @author takahara
 */
public class ArticleTreeItem extends TreeItem<ArticleModel> implements EventHandler<TreeItem.TreeModificationEvent<ArticleModel>> {
    
    private final ArticleModel articleModel;

    public ArticleTreeItem(ArticleModel articleModel) {
        this.articleModel = articleModel;
        this.setValue(articleModel);
        
        this.addEventHandler(TreeItem.<ArticleModel>branchExpandedEvent(), this);
        
    }
    
    @Override
    public boolean isLeaf() {
        return false;
    }
    
    /**
     * ファイルの取得
     * @return 
     */
    public ArticleModel getModel() {
        return this.articleModel;
    }

    /**
     * OPENイベント
     * @param e 
     */
    @Override
    public void handle(TreeModificationEvent<ArticleModel> e) {

        final ArticleTreeItem treeItem = (ArticleTreeItem) e.getSource();

        // 子がない要素だけが対象
        if (treeItem.getChildren().isEmpty()) {

            MainController.getInstance().getArticleLoadListTask().setOnSucceeded(new EventHandler<WorkerStateEvent>() {
                @Override
                public void handle(WorkerStateEvent t) {

                    List<ArticleTreeItem> categoryList = (List<ArticleTreeItem>) t.getSource().getValue();
                    treeItem.getChildren().setAll(categoryList);

                    MainController.getInstance().getArticleTreeView().getSelectionModel().select(treeItem);
                }
            });

            MainController.getInstance().getArticleLoadListTask().run(treeItem.getModel().getKey());
        }
    }
    
}
